package com.example.bishe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bishe.entity.Approval;
import com.example.bishe.entity.Room;
import com.example.bishe.entity.User;
import com.example.bishe.entity.UserRoom;
import com.example.bishe.mapper.ApprovalMapper;
import com.example.bishe.mapper.RoomMapper;
import com.example.bishe.mapper.UserRoomMapper;
import com.example.bishe.service.RoomService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bishe.web.b.vo.getRoomPageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  空间服务实现类
 * </p>
 *
 * @author LDH
 * @since 2022/11/30
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements RoomService {

    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private UserRoomMapper userRoomMapper;
    @Autowired
    private ApprovalMapper approvalMapper;

    /**
    * @Description: 分页查询空间信息
    * @Param: [pageNum, pageSize, name, startTime, endTime, state, type, userName, userMIN, userMAX]
    * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.example.bishe.web.b.vo.getRoomPageVO>
    * @Author: LDH
    * @Date: 2023/02/05
    */
    @Override
    public IPage<getRoomPageVO> roomPage(int pageNum, int pageSize, String name, String startTime, String endTime, String state, String type, String userName, Integer userMIN, Integer userMAX) {
        Page<getRoomPageVO> page = new Page<>(pageNum,pageSize);
        return roomMapper.getPage(page,name,startTime,endTime,state,type,userName,userMIN,userMAX);
    }

    /**
    * 功能描述: 批量删除空间
    * @Param: [rooms]
    * @return: void
    * @Author: LDH
    * @Date: 2023/05/08
    */
    @Override
    public void delBatch(List<Room> rooms) {
        rooms.forEach(room -> {
            // 删除空间内成员
            LambdaQueryWrapper<UserRoom> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRoom::getRoomId,room.getId());
            userRoomMapper.delete(queryWrapper);

            // 删除空间
            baseMapper.deleteById(room.getId());
        });
    }

    /**
    * @Description: 将空间设置为启用状态
    * @Param: [id]
    * @return: void
    * @Author: LDH
    * @Date: 2023/02/05
    */
    @Override
    public void setON(Long id) {
        Room room = roomMapper.selectById(id);
        room.setState("ON");
        roomMapper.updateById(room);
    }

    /**
    * @Description: 将空间设置为禁用状态
    * @Param: [id]
    * @return: void
    * @Author: LDH
    * @Date: 2023/02/05
    */
    @Override
    public void setOFF(Long id) {
        Room room = roomMapper.selectById(id);
        room.setState("OFF");
        roomMapper.updateById(room);
    }

    /**
    * @Description: 删除空间
    * @Param: [id]
    * @return: void
    * @Author: LDH
    * @Date: 2023/02/05
    */
    @Override
    public void deleteOne(Long id) {
        LambdaQueryWrapper<UserRoom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRoom::getRoomId,id);
        userRoomMapper.delete(queryWrapper);

        baseMapper.deleteById(id);
    }

    /**
    * 功能描述: c端查询个人空间
    * @Param: [pageNum, pageSize, userId, type, title]
    * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.example.bishe.entity.Room>
    * @Author: LDH
    * @Date: 2023/03/20
    */
    @Override
    public IPage<Room> getCRoomPage(int pageNum, int pageSize, Long userId, String title) {
        IPage<Room> page = new Page<>(pageNum, pageSize);
        return roomMapper.getCPage(page,userId,title);
    }

    /**
    * 功能描述: 查找空间内用户列表
    * @Param: [pageNum, pageSize, roomId]
    * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.example.bishe.entity.User>
    * @Author: LDH
    * @Date: 2023/04/23
    */
    @Override
    public IPage<User> getUserOfRoom(int pageNum, int pageSize, Long roomId) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        return userRoomMapper.getUserByRoom(page,roomId);
    }

    /**
    * 功能描述: 用户创建互联空间
    * @Param: [userId, name, description, type]
    * @return: int
    * @Author: LDH
    * @Date: 2023/04/23
    */
    @Override
    public int add(Room room) {
        // 一个用户只能加入一个情侣空间
        List<Room> rooms = roomMapper.getRoomNumByUser(room.getUserId());
        if (room.getType() == 1) {
            List<Room> list = rooms.stream().filter(r -> r.getType() == 1).collect(Collectors.toList());
            if (list.size() != 0)
                return -2;
        }

        // 用户创建空间数已超10个，需要管理员审批
        List<Room> roomList = roomMapper.getRoomNumByUser(room.getUserId());
        if (roomList.size() >= 10) {
            Approval approval = new Approval();
            approval.setUserId(room.getUserId());
            approval.setType(0);
            approval.setDescribe(room.getDescription());
            approvalMapper.insert(approval);
            return -1;
        }
        // 创建空间
        Room room1 = new Room();
        room1.setUserId(room.getUserId());
        room1.setType(room.getType());
        room1.setName(room.getName());
        room1.setDescription(room.getDescription());
        roomMapper.insert(room1);
        UserRoom userRoom = new UserRoom();
        userRoom.setUserId(room.getUserId());
        userRoom.setRoomId(room1.getId());
        userRoomMapper.insert(userRoom);
        return 0;
    }

    /**
    * 功能描述: 用户申请加入互联空间
    * @Param: [userId, roomId]
    * @return: int
    * @Author: LDH
    * @Date: 2023/04/23
    */
    @Override
    public int join(UserRoom userRoom) {
        // 一个用户只能加入一个情侣空间
        List<Room> rooms = roomMapper.getRoomNumByUser(userRoom.getUserId());
        Room room = roomMapper.selectById(userRoom.getRoomId());
        if (room.getType() == 1) {
            List<Room> list = rooms.stream().filter(r -> r.getType() == 1).collect(Collectors.toList());
            if (list.size() != 0)
                return -3;
        }

        // 该用户已在空间内
        if (userRoomMapper.getUserRoomByOne(userRoom.getUserId(),userRoom.getRoomId()) != null){
            return -1;
        }
        if (approvalMapper.getApprovalByOne(userRoom.getUserId(),userRoom.getRoomId(),1) != null){
            return -2;
        }
        Approval approval = new Approval();
        approval.setType(1);
        approval.setUserId(userRoom.getUserId());
        approval.setRoomId(userRoom.getRoomId());
        approvalMapper.insert(approval);
        return 0;
    }

    /**
    * 功能描述: 用户退出、解散空间
    * @Param: [userRoom]
    * @return: void
    * @Author: LDH
    * @Date: 2023/04/27
    */
    public void delete(UserRoom userRoom){
        QueryWrapper<Room> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userRoom.getUserId());
        queryWrapper.eq("id",userRoom.getRoomId());
        Room room = roomMapper.selectOne(queryWrapper);
        // 如果是空间主人退出，则解算该空间内所有人，是成员退出的话则只删除他自己
        QueryWrapper<UserRoom> userRoomQueryWrapper = new QueryWrapper<>();
        if (room != null){
            roomMapper.deleteById(room);
            userRoomQueryWrapper.eq("room_id", room.getId());
        }
        else {
            userRoomQueryWrapper.eq("user_id", userRoom.getUserId());
            userRoomQueryWrapper.eq("room_id", userRoom.getRoomId());
        }
        userRoomMapper.delete(userRoomQueryWrapper);
    }
}
